// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------
import Common from './lib/Common';

const WEAPP_PREFIX = 'https://api.weixin.qq.com';
const WEAPP_AUTH_URL = '/sns/jscode2session?';
const WEAPP_CODE_URL = '/wxa/getwxacodeunlimit?';

import Tools from './lib/Tools.js';

export default  class WechatWeapp extends Common {

	/**
	 * 小程序登录
	 * @param  {String} $code      [description]
	 * @param  {String} $appid     [description]
	 * @param  {String} $appsecret [description]
	 * @return {[type]}            [description]
	 */
	async weappLogin( $code = '',$appid = '', $appsecret = ''){

		if (!$appid || !$appsecret) {
            $appid = this.$appid;
            $appsecret = this.$appsecret
        }

        let url = WEAPP_PREFIX + WEAPP_AUTH_URL + 'appid=' + $appid + '&secret=' + $appsecret+'&js_code='+$code+'&grant_type=authorization_code';

        let result = await request.get(url);
        if (result) {
            if (result.errcode) {
                this.errCode = result['errcode'];
                this.errMsg = result['errmsg'];
                return false;
            }

            return result;
        }
        return false;

	}

    /**
     * 获取微信二维码
     * @param  {[type]} $page  页面
     * @param  {[type]} $scene 参数
     * @return {[type]}        [description]
     */
    async weappQrcode(page, scene) {

        if (!await this.getAccessToken()) {
            return false;
        }

        let url = WEAPP_PREFIX + WEAPP_CODE_URL + "access_token=" + this.$access_token;
        let result = await Tools.httpPost(url,{page, scene},{responseType:'arraybuffer'});
        if (result) {
            if (result.errcode) {
                this.errCode = result['errcode'];
                this.errMsg = result['errmsg'];
                return false;
            }

            return result;
        }
        return false;
    }
}
